package io.kiki.stack.netty.channelManager;

import io.kiki.stack.netty.invoker.RequestContext;
import io.kiki.stack.netty.protocol.Protocol;
import io.kiki.stack.netty.protocol.ProtocolImpl;
import io.kiki.stack.netty.userProcessor.UserProcessor;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;

/**
 * Dispatch messages to corresponding protocol.
 */
@Slf4j
@Setter
@Getter
@ChannelHandler.Sharable
public class ChannelInboundHandlerAdapter extends io.netty.channel.ChannelInboundHandlerAdapter {
    private final boolean serverSide;

    private final ConcurrentHashMap<String, UserProcessor<?>> userProcessors;


    public ChannelInboundHandlerAdapter(boolean serverSide, ConcurrentHashMap<String, UserProcessor<?>> userProcessors) {
        this.serverSide = serverSide;
        this.userProcessors = userProcessors;
    }

    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {

        Protocol protocol = ProtocolImpl.protocol;
        protocol.getCommandHandler().handleCommand(new ChannelContext(channelHandlerContext, new RequestContext(), serverSide, userProcessors), msg);
        channelHandlerContext.fireChannelRead(msg);
    }
}
